package com.zjhb.common.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

import com.zjhb.common.util.ResourceUtil;
import com.zjhb.common.util.StringMyUtil;
import com.zjhb.entity.FileEntity;

//文件上传下载公共插件
public class UploadController {

	public static FileEntity uploadFile(MultipartFile file) {
		// 获取上传文件的名称
		Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
		Long random = (long) (Math.random() * now);
		String name = file.getOriginalFilename();
		String suffix = name.substring(name.lastIndexOf(".") + 1);
		String fileName = now + "" + random; 
		if (StringMyUtil.isNotEmpty(suffix)) {
			fileName = fileName + "." + suffix;
		}
		String path = "C://upload";
		File file2 = new File(path);
		if (!file2.exists()) {
			// 创建临时目录
			file2.mkdir();
		}
		try {
			// 文件存放的路径
			FileOutputStream fileOutputStream = new FileOutputStream(file2 + "/" + fileName);
			fileOutputStream.write(file.getBytes());
			fileOutputStream.flush();
			fileOutputStream.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		FileEntity fileEntity = new FileEntity();
		fileEntity.setCreateTime(ResourceUtil.getNowTime());
		fileEntity.setFileId(file2 + "/" + fileName);
		fileEntity.setName(name);
		return fileEntity;
	}

	public static void deleteFile(String filekey, String fileName) {
		String[] keys = filekey.split(",");
		for (String key : keys) {
			File file = new File(key);
			if (file != null) {
				file.delete();
			}

		}

	}

	public static void downloadFile(String filekey, String name, HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		try {
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(name.getBytes("gb2312"), "ISO8859-1"));
			File file = new File(filekey);
			InputStream inputStream = new FileInputStream(file);
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[1024];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			inputStream.close();
			os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		String userName="parent13057633772";
		System.out.println(userName.replaceAll("parent", ""));;
	}
}
